<template>
  <div id="eveRegSave">
    <div><span style="padding: 0 20px;line-height: 60px;font-size: 20px">推广客户</span></div>
    <el-form :inline="true" :model="search" class="demo-form-inline" style="padding: 0 20px;">
      <el-form-item label="活动">
        <el-select v-model="search.eventId" placeholder="请选择活动">
          <el-option label="全部" value=""/>
          <el-option v-for="(item,k) in eveList" :label="item.title" :value="item.eventId" :key="k"/>
        </el-select>
      </el-form-item>
      <el-form-item label="来源">
        <el-select v-model="search.settingId" placeholder="请选择来源">
          <el-option label="全部" value=""/>
          <el-option v-for="(item,k) in sorList" :label="item.value" :value="item.settingId" :key="k"/>
        </el-select>
      </el-form-item>
      <el-form-item label="企业名称">
        <el-input v-model="search.name" placeholder="请输入企业名称" @keypress.native.enter="getPageList"/>
      </el-form-item>
      <el-form-item label="联系人">
        <el-input v-model="search.contact" placeholder="请输入联系人" @keypress.native.enter="getPageList"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="search.turSta" placeholder="请选择状态">
          <el-option label="全部" value=""/>
          <el-option label="已转入" value="1"/>
          <el-option label="未转入" value="0"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getPageList">查询</el-button>
      </el-form-item>
    </el-form>
    <div style="text-align: right;padding-right: 20px;padding-bottom: 8px;">
      <el-button type="primary" @click="allTurEveTo" >批量转入客户</el-button>
    </div>
    <div xs-empty-icon="nopermission" xs-empty-text="暂无权限" >
      <el-table v-loading="loading" id="psi-table" :data="list" :height="tableHeight"
          class="n-table--border" stripe  border highlight-current-row
        style="width: 100%;" @selection-change="handleSelectionChange">
        <el-table-column type="selection" :selectable="checkSelectable" width="55">
        </el-table-column>
        <el-table-column v-for="(item, index) in fieldList" :key="index" :fixed="index==0"
          :prop="item.fieldName" :label="item.name" width="150">
          <template slot-scope="scope">
            <div  v-if="item.fieldName == 'turSta'" :title="scope.row[item.fieldName]" class="table-head-name">
              <span v-if="scope.row[item.fieldName] == '0' && scope.row['compCnt'] == 0 " style="color: orangered;">未转入 </span>
              <span v-if="scope.row[item.fieldName] == '0' && scope.row['compCnt'] > 0 " style="color: green;">已存在 </span>
              <span v-if="scope.row[item.fieldName] == '1'" style="color: green;">已转入 </span>
            </div>
            <div  v-else :title="scope.row[item.fieldName]" class="table-head-name">{{ scope.row[item.fieldName] }}</div>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          min-width="120">
          <template slot-scope="scope">
            <el-button v-if="scope.row.turSta == '0' && scope.row.compCnt == 0 " type="text" size="small"  @click.native.prevent="turEveTo(scope.row)">
              转入客户
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="p-contianer">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size.sync="pageSize"
          :total="total"
          class="p-bar"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>
    </div>
    <el-dialog title="转入" :visible.sync="dialogTableVisible" @closed="zrClosed">
      <el-form ref="zr" :model="zr" :rules="rules" label-width="80px" size="mini">
        <el-form-item label="客户类型" prop="customer_type">
          <el-select v-model="zr.customer_type" placeholder="请选择客户类型">
            <el-option label="潜在客户" value="1"></el-option>
            <el-option label="目标客户" value="2"></el-option>
          </el-select>
        </el-form-item>
       <!-- <el-form-item label="审核信息" prop="ckUserId">

          &lt;!&ndash;<xh-user-cell v-if="reFresh && examineInfo.examineType===2"
            :info-type="zr.ckUserId"
            :value="draftUser ? [draftUser] : []"
            @value-change="fieldValueChange"/>&ndash;&gt;
        </el-form-item>-->
      </el-form>
      <!-- 审核信息 -->
      <create-sections
        title="审核信息">
        <div
          v-if="examineInfo.examineType===1 || examineInfo.examineType===2"
          slot="header"
          class="examine-type">{{ examineInfo.examineType===1 ? '固定审批流' : '授权审批人' }}</div>
        <create-examine-info
          ref="examineInfo"
          types-id=""
          types="crm_leads"
          @value-change="examineValueChange"/>
      </create-sections>
      <div style="text-align: center">
        <el-button type="primary" @click="zrSubm('zr')">确定</el-button>
        <el-button @click="zrClr('zr')">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { queryEveRegListHead,eveListForSlt,crmCreateExamineFlow,getPvsResource } from '@/api/eventmanagement/common'
import { queryEveRegList,turEvereg,allTurEvereg } from '@/api/eventmanagement/event-reg'
import { XhUserCell } from '@/components/CreateCom'
import CreateExamineInfo from '@/components/Examine/CreateExamineInfo'
import CreateSections from '@/components/CreateSections'
export default {
  name: 'PromoteCustomerIndex',
  components: {
    XhUserCell,
    CreateExamineInfo, // 审核信息
    CreateSections
  },
  filter:{
    contentFilters: function(array) {
      return array
        .map(item => {
          return item.realname
        })
        .join('、')
    }
  },
  data() {
    return {
      turType:'',
      selRows:[],
      // 审批信息
      examineInfo: {},
      eveList:[],
      sorList:[],
      reFresh:false,
      dialogTableVisible:false,
      psiType: 'house',
      loading: false, // 加载动画
      fieldList: [],
      list: [],
      currentPage: 1,
      pageSize: 15,
      pageSizes: [15, 30, 60, 100],
      total: 0,
      search: {
        eventId:'',
        settingId:'',
        name: '',
        contact: '',
        turSta: ''
      },
      draftUser: null,
      zr:{
        customer_type: '1',
        ckUserId: ''
      },
      tprow: {},
      rules: {
        customer_type: [
          { required: true, message: '请选择客户类型', trigger: 'change' }
        ],
        ckUserId: [
          { required: true, message: '请选择审批人', trigger: 'change' }
        ],
      },
      tableHeight: document.documentElement.clientHeight - 225
    }

  },
  mounted() {
    this.eveListForSlt()
    this.sorListForSlt()
    this.getHeaderList()
    this.getPageList()
    this.crmCreateExamineFlow()
  },
  methods: {
// 审批信息值更新
    examineValueChange(data) {
      this.examineInfo = data
    },
    eveListForSlt(){
      eveListForSlt().then(res => {
        this.eveList = res.data;
      })
        .catch(()=>{

        })
    },
    sorListForSlt(){
      getPvsResource().then(res => {
        this.sorList = res.data;
      })
        .catch(()=>{

        })
    },
    // 审批流
    crmCreateExamineFlow(){
      crmCreateExamineFlow({categoryType: '4'}).then(res => {
        this.examineInfo = res.data
      })
    },
    checkSelectable(row){
      return row.turSta == '0' && row.compCnt == 0
    },
    handleSelectionChange(val){
      this.selRows = val;
    },
    // 批量转入
    allTurEveTo(){
      if(this.selRows.length < 1){
        this.$message.warning("请至少选择一条数据")
        return;
      }
      this.turType = '1'
      this.dialogTableVisible = true;
    },
    // 转入企业
    turEveTo(row){
      this.turType = '0'
      this.tprow = row;
      this.dialogTableVisible = true;
    },
    zrClosed(){
      this.draftUser = null
      this.zr.ckUserId = ''
      this.reFresh = false;
    },
    zrSubm(fm){
      // 客户来源  批量转入
      this.$refs[fm].validate((valid) => {
        if (valid) {
          if(this.turType == '0'){
            let c_f = {
              entity:{
                customer_contacts:[{
                  name: this.tprow.contact,
                  mobile: this.tprow.phone,
                }],
                customerName: this.tprow.name,
                telephone: this.tprow.phone,
                ownerUserid: this.tprow.ownerUserId,
                address: this.tprow.address,
                detailAddress:this.tprow.addressDetail,
                followup: 0,
              },
              field: [{
                fieldId: 18,
                fieldName:	"客户来源",
                fieldType:	0,
                formType:	"select",
                inputTips:	null,
                isDisabled:	0,
                isNull:	0,
                isUnique:	0,
                name:	"客户来源",
                options:	"促销,搜索引擎,广告,转介绍,线上注册,线上询价,预约上门,陌拜,电话咨询,邮件咨询,电话推广",
                type:3,
                value:	"市场推广",
                setting:["促销","搜索引擎","广告","转介绍", "线上注册","线上询价","预约上门","陌拜", "电话咨询","邮件咨询","电话推广"]
              },{
                fieldId: 19,
                fieldName:	"客户行业",
                fieldType:	0,
                formType:	"select",
                inputTips:	null,
                isDisabled:	0,
                isNull:	0,
                isUnique:	0,
                name:	"客户行业",
                options:	"促销,搜索引擎,广告,转介绍,线上注册,线上询价,预约上门,陌拜,电话咨询,邮件咨询,电话推广",
                type:3,
                value:	this.tprow.customerIndustry,
                setting:["促销","搜索引擎","广告","转介绍", "线上注册","线上询价","预约上门","陌拜", "电话咨询","邮件咨询","电话推广"]
              }],
              owner_user_id:this.tprow.ownerUserId,
              checkUserId: this.examineInfo.value&&this.examineInfo.value[0]&&this.examineInfo.value[0].userId?this.examineInfo.value[0].userId:null,
              customer_type: this.zr.customer_type*1,
              businessInfo: this.strToJSON(this.tprow.companyInfo),
              regId: this.tprow.regId
            }
            if(this.examineInfo.examineType == 2 &&
              (c_f.checkUserId == null || c_f.checkUserId == '')){
              this.$message.error("审批人不能为空")
              return
            }
            this.loading = true
            turEvereg(c_f).then(res => {
              this.dialogTableVisible = false;
              this.loading = false
              this.$message.success('操作成功')
              this.getPageList()
            })
              .catch(() => {
                this.loading = false
              })
          }else if(this.turType = '1'){
            let c_f_s = []
            this.selRows.forEach(item=>{
              let c_f = {
                field: [{
                  fieldId: 18,
                  fieldName:	"客户来源",
                  fieldType:	0,
                  formType:	"select",
                  inputTips:	null,
                  isDisabled:	0,
                  isNull:	0,
                  isUnique:	0,
                  name:	"客户来源",
                  options:	"促销,搜索引擎,广告,转介绍,线上注册,线上询价,预约上门,陌拜,电话咨询,邮件咨询,电话推广",
                  type:3,
                  value:	"市场推广",
                  setting:["促销","搜索引擎","广告","转介绍", "线上注册","线上询价","预约上门","陌拜", "电话咨询","邮件咨询","电话推广"]
                },{
                  fieldId: 19,
                  fieldName:	"客户行业",
                  fieldType:	0,
                  formType:	"select",
                  inputTips:	null,
                  isDisabled:	0,
                  isNull:	0,
                  isUnique:	0,
                  name:	"客户行业",
                  options:	"促销,搜索引擎,广告,转介绍,线上注册,线上询价,预约上门,陌拜,电话咨询,邮件咨询,电话推广",
                  type:3,
                  value:	item.customerIndustry,
                  setting:["促销","搜索引擎","广告","转介绍", "线上注册","线上询价","预约上门","陌拜", "电话咨询","邮件咨询","电话推广"]
                }],
                entity:{
                  customer_contacts:[{
                    name: item.contact,
                    mobile: item.phone,
                  }],
                  customerName: item.name,
                  telephone: item.phone,
                  ownerUserid: item.ownerUserId,
                  address: item.address,
                  detailAddress:item.addressDetail,
                  followup: 0,
                },
                owner_user_id:item.ownerUserId,
                checkUserId: this.examineInfo.value&&this.examineInfo.value[0]&&this.examineInfo.value[0].userId?this.examineInfo.value[0].userId:null,
                customer_type: this.zr.customer_type*1,
                businessInfo: this.strToJSON(item.companyInfo),
                regId: item.regId
              }
              c_f_s.push(c_f)
            })
            let ae = true;
            c_f_s.forEach(c_f =>{
              if(this.examineInfo.examineType == 2 &&
                (c_f.checkUserId == null || c_f.checkUserId == '')){
                ae = false;
                return
              }
            })
            if(!ae){
              this.$message.error("审批人不能为空")
              return;
            }
            allTurEvereg({list:c_f_s}).then(res => {
              this.dialogTableVisible = false;
              this.$alert('成功 <span style="color:green">'+res.data.rg+'</span> 条,' +
                '失败 <span style="color:red">'+res.data.err+'</span> 条', '提示', {
                dangerouslyUseHTMLString: true
              });
              this.getPageList();
            })
              .catch(()=>{

              })
          }

        } else {
          return false;
        }
      });

    },
    zrClr(){
      this.dialogTableVisible = false;
    },
    // 字段的值更新
    fieldValueChange(data) {
      if (data.value.length) {
        this.draftUser = data.value[0]
        this.zr.ckUserId= this.draftUser.userId
      } else {
        this.draftUser = null
        this.zr.ckUserId = ''
      }
      this.$emit('value-change', {
        examineType: this.examineInfo.examineType, // 审批类型
        value: data.value // 审批信息
      })
      this.$refs.form.validateField('name')
    },
    // 获取表头
    getHeaderList() {
      queryEveRegListHead()
        .then(res => {
          this.fieldList = res.data
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 获取数据
    getPageList() {
      this.loading = true
      var praprm = this.search
      praprm['page'] = this.currentPage
      praprm['limit'] = this.pageSize
      queryEveRegList(praprm)
        .then(res => {
          this.list = res.data.list
          this.total = res.data.totalRow
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 更改每页展示数量
    handleSizeChange(val) {
      this.pageSize = val
      this.getPageList()
    },
    // 更改当前页数
    handleCurrentChange(val) {
      this.currentPage = val
      this.getPageList()
    },
    strToJSON(str) {
      if (typeof str == 'string') {
        try {

          return JSON.parse(str);;
        } catch(e) {
          return {};
        }
      }
      return {}
    }
  }
}
</script>


<style lang="scss" scoped>
  @import '../../psimanagement/styles/table.scss';
  // 审核信息 里的审核类型
  .examine-type {
    font-size: 12px;
    color: white;
    background-color: #fd715a;
    padding: 0 8px;
    margin-left: 5px;
    height: 16px;
    line-height: 16px;
    border-radius: 8px;
    transform: scale(0.8, 0.8);
  }

</style>

